package com.kxf.rpc.client;

import com.kxf.rpc.entity.RPCRequest;
import com.kxf.rpc.entity.RPCResponse;
import com.kxf.rpc.loadbalance.CommonLoadBalance;
import com.kxf.rpc.loadbalance.ConsistentHashLoadBalance;
import com.kxf.rpc.registry.redis.RedisServiceDiscovery;
import com.kxf.rpc.serializer.CommonSerialize;
import com.kxf.rpc.serializer.JsonSerializer;
import com.kxf.rpc.transport.ObjectReader;
import com.kxf.rpc.transport.ObjectWriter;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * @author Kxf
 * @create 2021/9/22,0022 16:33
 */
public class JdkClient implements CommonClient {

    private CommonSerialize commonSerialize;

    public JdkClient() {
        this.commonSerialize = new JsonSerializer();
    }

    public JdkClient(int serializerCode) {
        this.commonSerialize = CommonSerialize.getByteCode(serializerCode);
    }

    @Override
    public RPCResponse sendRequest(RPCRequest request) throws Exception {
        //随机负载均衡算法
        //InetSocketAddress address = new RedisServiceDiscovery().getInetByInterfaceName(request.getInterfaceName());
        //一致性Hash负载均衡算法
        InetSocketAddress address = new RedisServiceDiscovery(CommonLoadBalance.getByCode(1)).
                getInetByInterfaceName(request.getInterfaceName());
        Socket socket = new Socket(address.getAddress().getHostAddress(), address.getPort());
        OutputStream outputStream = socket.getOutputStream();
        InputStream inputStream = socket.getInputStream();
        ObjectWriter.write(outputStream, commonSerialize, request);
        /*传输结束后开始等待接收服务端响应的数据*/
        RPCResponse response;
        response = (RPCResponse) ObjectReader.read(inputStream);
        return response;
    }
}
